package com.xhs.util;

import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 帖子时间解析工具类
 * 用于解析小红书帖子的发布时间并判断是否超过时间限制
 *
 * @author xhs
 */
@Slf4j
public class PostTimeUtil {

    private static final Pattern MINUTE_PATTERN = Pattern.compile("(\\d+)分钟前");
    private static final Pattern HOUR_PATTERN = Pattern.compile("(\\d+)小时前");
    private static final Pattern DAY_PATTERN = Pattern.compile("(\\d+)天前");
    private static final Pattern YESTERDAY_TIME_PATTERN = Pattern.compile("昨天\\s+(\\d{1,2}):(\\d{2})");
    private static final Pattern DATE_PATTERN = Pattern.compile("(\\d{2})-(\\d{2})");

    /**
     * 判断帖子是否超过时间限制
     *
     * @param timeText 时间文本，如"39分钟前"、"昨天 22:42"、"1天前"等
     * @param limitDays 时间限制（天）
     * @return true表示超过限制，false表示在限制内
     */
    public static boolean isPostTimeExceeded(String timeText, Integer limitDays) {
        if (timeText == null || timeText.trim().isEmpty()) {
            log.warn("时间文本为空，默认认为超过限制");
            return true;
        }

        if (limitDays == null || limitDays <= 0) {
            log.warn("时间限制无效，默认认为超过限制");
            return true;
        }

        try {
            LocalDateTime postTime = parsePostTime(timeText);
            if (postTime == null) {
                log.warn("无法解析时间文本: {}", timeText);
                return true;
            }

            LocalDateTime now = LocalDateTime.now();
            LocalDateTime limitTime = now.minusDays(limitDays);

            // 如果帖子时间早于限制时间，则认为超过限制
            boolean exceeded = postTime.isBefore(limitTime);
            
            log.debug("帖子时间: {}, 限制时间: {}, 是否超过限制: {}", postTime, limitTime, exceeded);
            
            return exceeded;

        } catch (Exception e) {
            log.error("解析时间失败: {}", timeText, e);
            return true;
        }
    }

    /**
     * 解析帖子时间文本为LocalDateTime
     *
     * @param timeText 时间文本
     * @return 解析后的时间，失败返回null
     */
    private static LocalDateTime parsePostTime(String timeText) {
        LocalDateTime now = LocalDateTime.now();
        
        // 处理"X分钟前"
        Matcher minuteMatcher = MINUTE_PATTERN.matcher(timeText);
        if (minuteMatcher.find()) {
            int minutes = Integer.parseInt(minuteMatcher.group(1));
            return now.minusMinutes(minutes);
        }

        // 处理"X小时前"
        Matcher hourMatcher = HOUR_PATTERN.matcher(timeText);
        if (hourMatcher.find()) {
            int hours = Integer.parseInt(hourMatcher.group(1));
            return now.minusHours(hours);
        }

        // 处理"X天前"
        Matcher dayMatcher = DAY_PATTERN.matcher(timeText);
        if (dayMatcher.find()) {
            int days = Integer.parseInt(dayMatcher.group(1));
            return now.minusDays(days);
        }

        // 处理"昨天 HH:mm"
        Matcher yesterdayMatcher = YESTERDAY_TIME_PATTERN.matcher(timeText);
        if (yesterdayMatcher.find()) {
            int hour = Integer.parseInt(yesterdayMatcher.group(1));
            int minute = Integer.parseInt(yesterdayMatcher.group(2));
            return now.minusDays(1).withHour(hour).withMinute(minute).withSecond(0).withNano(0);
        }

        // 处理"MM-dd"格式（认为是今年的日期）
        Matcher dateMatcher = DATE_PATTERN.matcher(timeText);
        if (dateMatcher.find()) {
            int month = Integer.parseInt(dateMatcher.group(1));
            int day = Integer.parseInt(dateMatcher.group(2));
            
            // 如果月份和日期比当前时间晚，可能是去年的日期
            LocalDateTime thisYearDate = LocalDateTime.of(now.getYear(), month, day, 0, 0, 0);
            if (thisYearDate.isAfter(now)) {
                thisYearDate = thisYearDate.minusYears(1);
            }
            
            return thisYearDate;
        }

        // 如果都匹配不上，返回null
        return null;
    }

    /**
     * 测试方法，用于验证时间解析是否正确
     */
    public static void main(String[] args) {
        String[] testTimes = {
            "39分钟前",
            "1小时前",
            "昨天 22:42",
            "昨天 14:14",
            "1天前",
            "4天前",
            "6天前",
            "07-13"
        };

        System.out.println("当前时间: " + LocalDateTime.now());
        
        for (String timeText : testTimes) {
            LocalDateTime parsedTime = parsePostTime(timeText);
            boolean exceeded1Day = isPostTimeExceeded(timeText, 1);
            boolean exceeded4Days = isPostTimeExceeded(timeText, 4);
            
            System.out.printf("时间文本: %-12s -> 解析结果: %-20s, 超过1天: %s, 超过4天: %s%n", 
                timeText, parsedTime, exceeded1Day, exceeded4Days);
        }
    }
} 